package com.example.carpro


import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.os.Bundle
import android.view.Display
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.appcompat.content.res.AppCompatResources.getDrawable
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.Popup
import com.blankj.utilcode.util.AppUtils
import com.example.carpro.domain.*
import com.example.carpro.ui.theme.CarProTheme
import com.example.carpro.ui.theme.LightBlue
import com.example.carpro.ui.theme.SkyBlue
import com.example.carpro.utils.getLunarDate
import com.example.carpro.utils.transForData
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import kotlinx.coroutines.*
import java.util.*


class MainActivity : ComponentActivity() {

    @ExperimentalFoundationApi
    @InternalCoroutinesApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CarProTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    color = MaterialTheme.colors.background, modifier = Modifier.fillMaxSize()
                ) {
                    HomePage()

                }
            }
        }
    }


    @ExperimentalFoundationApi
    @Composable
    fun HomePage(
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.linearGradient(listOf(LightBlue, SkyBlue))
                )
        ) {
            Row(modifier = Modifier.weight(1f, true)) {
                Column(modifier = Modifier.weight(1f)) {
                    GetWeather()
                    GetDateTime()
                }
                Column(modifier = Modifier.weight(3f)) {

                }
            }
            BottomBar(appInfoList = getOwnerAppList())
        }

    }

    //原始方法
    private fun getOwnerAppList(): List<AppUtils.AppInfo> {
        val appsInfo = AppUtils.getAppsInfo()
        return appsInfo.filter { item -> !item.isSystem }
    }

    @Composable
    fun GetWeather() {
        var weatherDataState by remember { mutableStateOf(WeatherDataDetail()) }
        LaunchedEffect(key1 = Unit) {
            //模拟网络请求
            delay(50)
            weatherDataState =
                transForData<WeatherData>(this@MainActivity, "weather")
                    .data
        }
        WeatherCard(weatherDataState)
    }


    @Composable
    fun WeatherCard(weatherData: WeatherDataDetail, modifier: Modifier = Modifier) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(120.dp)
                .padding(8.dp)
        ) {
            Column(
                verticalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.padding(8.dp)
            ) {
                Text(
                    text = "天气", color = Color.Gray,
                    fontSize = 16.sp
                )
                Text(
                    text = "${weatherData.intervalTemperature}",
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center,
                    fontSize = 18.sp
                )
                Text(
                    text = "${weatherData.area} ${weatherData.weatherConditions} ${weatherData.descriptionOfTheCurrentWindDirection}",
                    color = Color.Gray,
                    fontSize = 16.sp
                )

            }
        }
    }

    @Composable
    fun open2Dialog(
        cancel: () -> Unit,
        firstButton: () -> Unit,
        secondButton: () -> Unit
    ) {

        Popup(
            alignment = Alignment.Center, onDismissRequest = cancel
        ) {
            Card(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(20.dp)
                    .background(Color.White)
            ) {
                Column() {
                    TextButton(onClick = firstButton) {
                        Text("替换其App", fontSize = 10.sp)
                    }
                    TextButton(onClick = secondButton) {
                        Text("副屏显示", fontSize = 10.sp)
                    }
                }
            }

        }
    }

    @ExperimentalFoundationApi
    @Composable
    fun BottomBar(
        appInfoList: List<AppUtils.AppInfo>,
        modifier: Modifier = Modifier
    ) {
        val context = LocalContext.current
        var openDialog by remember {
            mutableStateOf(false)
        }
        var clickIndex by remember {
            mutableStateOf(-1)
        }
        var longClickIndex by remember {
            mutableStateOf(-1)
        }

        val list = remember {
            val list12 = mutableStateListOf<AppUtils.AppInfo>()
            repeat(5) {
                val info = AppUtils.AppInfo(
                    "test",
                    "test", getDrawable(context, R.drawable.ic_baseline_add_24),
                    "test", "v1", 1, 29, 29, false
                )
                list12.add(info)
            }
            list12
        }
        Card(
            modifier = Modifier
                .padding(start = 50.dp, end = 50.dp)
        ) {

            LazyRow(
                contentPadding = PaddingValues(8.dp),
                modifier = Modifier
                    .background(Color.White)
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {

                itemsIndexed(list) { index, it ->
                    Box() {
                        Card(modifier = Modifier.combinedClickable(
                            onClick = {
                                clickIndex = index
                                if (list[clickIndex].name == "test") {
                                    openDialog = true
                                } else {
                                    val packageManager = context.packageManager
                                    val intent =
                                        packageManager.getLaunchIntentForPackage(list[clickIndex].packageName)
                                    startActivity(intent)
                                }
                            },
                            onLongClick = {
                                //长按逻辑
                                longClickIndex = index
                            }
                        )) {
                            Image(
                                painter = rememberDrawablePainter(
                                    drawable = list[index].icon
                                ),
                                contentDescription = "", modifier = Modifier.size(48.dp)
                            )
                        }
                        if (longClickIndex == index) {
                            open2Dialog(
                                cancel = { longClickIndex = -1 }, firstButton = {
                                    longClickIndex = -1
                                    openDialog = true
                                }) {
                                longClickIndex = -1
                                launchSecondScreen(list[index].packageName)
                            }
                        }
                    }


                }
            }
        }
        if (openDialog) {
            chooseDialog(cancel = {
                openDialog = false
            }, appChoose = {
                if (clickIndex != -1) {
                    list[clickIndex] = it
                }
                openDialog = false
            }, appInfoList)
        }

    }


    private fun launchSecondScreen(packageName: String) {
        val displayManager =
            getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
        val displays: Array<Display> = displayManager.getDisplays()
        val options = ActivityOptions.makeBasic();
        // display to sub screen
        options.setLaunchDisplayId(
            displays.get(displays.size - 1).displayId); //这里display0是第一块屏；display1是第二块屏
        try {
            val intent =
                packageManager.getLaunchIntentForPackage(packageName)

            intent!!.addFlags(
                Intent.FLAG_ACTIVITY_MULTIPLE_TASK
                        or Intent.FLAG_ACTIVITY_NEW_TASK
                        or Intent.FLAG_ACTIVITY_SINGLE_TOP
            )
            startActivity(intent, options.toBundle());
        } catch (e: Exception) {

        }
    }


    @ExperimentalFoundationApi
    @Composable
    fun chooseDialog(
        cancel: () -> Unit,
        appChoose: (AppUtils.AppInfo) -> Unit,
        appList: List<AppUtils.AppInfo>
    ) {
        Dialog(onDismissRequest = cancel) {
            LazyVerticalGrid(
                cells = GridCells.Adaptive(48.dp),
                modifier = Modifier.background(Color.White)
            ) {
                items(appList) { it ->
                    Column(
                        modifier = Modifier
                            .size(48.dp)
                            .padding(8.dp)
                            .clickable {
                                appChoose(it)
                            },
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = rememberDrawablePainter(
                                drawable = it.icon
                            ),
                            contentDescription = "${it.name}",
                            modifier = Modifier.size(20.dp)
                        )
                        Text(text = "${it.name}", fontSize = 8.sp)
                    }

                }
            }

        }
    }

    @Composable
    fun GetDateTime() {
        val initTimeDetail = Calendar.getInstance().run {
            TimeDetail(
                year = get(Calendar.YEAR),
                month = get(Calendar.MONTH + 1), // Kotlin months are 0-based
                day = get(Calendar.DATE),
                hour = get(Calendar.HOUR),
                minute = get(Calendar.MINUTE),
                second = get(Calendar.SECOND),
                lunarDateString = getLunarDate()
            )
        }
        var currentTime by remember { mutableStateOf(initTimeDetail) }
        LaunchedEffect(Unit) {
            withContext(Dispatchers.IO) {
                while (true) {
                    currentTime = Calendar.getInstance().run {
                        TimeDetail(
                            year = get(Calendar.YEAR),
                            month = get(Calendar.MONTH + 1),
                            day = get(Calendar.DATE),
                            hour = get(Calendar.HOUR),
                            minute = get(Calendar.MINUTE),
                            second = get(Calendar.SECOND),
                            lunarDateString = getLunarDate()
                        )
                    }
                    delay(1000L)
                }
            }
        }
        TimesCard(timeDetail = currentTime)
    }


    @Composable
    fun TimesCard(timeDetail: TimeDetail, modifier: Modifier = Modifier) {
        Card(
            modifier = modifier
                .padding(8.dp)
                .fillMaxWidth()
                .height(80.dp)
        ) {
            Column(
                modifier = Modifier
                    .padding(8.dp)
                    .wrapContentHeight()
            ) {
                Row(
                    modifier = Modifier.wrapContentHeight()
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = "${timeDetail.hour}:${timeDetail.minute}:${timeDetail.second}",
                            modifier = Modifier.weight(1f),
                            fontSize = 20.sp, fontWeight = FontWeight.Bold
                        )
                        Spacer(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(2.dp)
                        )
                        Text(
                            text = "${timeDetail.year}年${timeDetail.month}月${timeDetail.day}日"
                        )
                    }
                    Text(text = "${timeDetail.lunarDateString}")
                }

            }

        }
    }
}


